package com.ricky.chat.client.dialog;

import com.ricky.chat.common.dto.JsonMsgDto;
import com.ricky.chat.client.server.RickyClient;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Swing聊天界面实现 - 登录模式
 */
public class ChatWindow extends JFrame {
    private final static Logger LOGGER = LoggerFactory.getLogger(RickyClient.class);

    // 卡片布局相关组件
    private JPanel mainPanel;
    private CardLayout cardLayout;

    // 登录界面组件
    private JPanel loginPanel;
    private JTextField loginUsernameField;
    private JPasswordField loginPasswordField;
    private JButton loginButton;
    private JButton switchToRegisterButton;
    private JLabel loginTitleLabel;

    // 注册界面组件
    private JPanel registerPanel;
    private JTextField registerUsernameField;
    private JPasswordField registerPasswordField;
    private JButton registerButton;
    private JButton switchToLoginButton;

    // 连接界面组件
    private JPanel connectPanel;
    private JButton connectServerButton;
    private JLabel serverInfoLabel;

    // 聊天界面组件
    private JPanel chatPanel;
    private static JTextArea chatArea;
    private JTextField inputField;
    private JButton sendButton;
    private JButton disconnectButton;
    private JScrollPane scrollPane;

    // 在线用户列表组件
    private JList<String> onlineUsersList;
    private DefaultListModel<String> onlineUsersModel;
    private JScrollPane onlineUsersScrollPane;

    private Channel channel;
    private boolean isConnected = false;
    private String currentUser;

    public ChatWindow() {
        initializeComponents();
        setupLayout();
        setupEventHandlers();
        setupWindowProperties();
    }

    private void initializeComponents() {
        // 初始化卡片布局
        mainPanel = new JPanel();
        cardLayout = new CardLayout();
        mainPanel.setLayout(cardLayout);

        // 初始化登录界面组件
        loginPanel = new JPanel();
        loginTitleLabel = new JLabel("用户登录");
        loginTitleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        loginUsernameField = new JTextField(15);
        loginPasswordField = new JPasswordField(15);
        loginButton = new JButton("登录");
        switchToRegisterButton = new JButton("没有账号？去注册");
        switchToRegisterButton.setBorder(BorderFactory.createEmptyBorder());
        switchToRegisterButton.setForeground(Color.BLUE);
        switchToRegisterButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        switchToRegisterButton.setContentAreaFilled(false);

        // 初始化注册界面组件
        registerPanel = new JPanel();
        registerUsernameField = new JTextField(15);
        registerPasswordField = new JPasswordField(15);
        registerButton = new JButton("注册");
        switchToLoginButton = new JButton("已有账号？去登录");
        switchToLoginButton.setBorder(BorderFactory.createEmptyBorder());
        switchToLoginButton.setForeground(Color.BLUE);
        switchToLoginButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        switchToLoginButton.setContentAreaFilled(false);

        // 初始化连接界面组件
        connectPanel = new JPanel();
        connectServerButton = new JButton("连接服务器");
        connectServerButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        connectServerButton.setPreferredSize(new Dimension(120, 40));
        serverInfoLabel = new JLabel(String.format("服务器地址: %s:%d", RickyClient.SERVER_IP, RickyClient.SERVER_PORT));
        serverInfoLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));

        // 初始化聊天界面组件
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        chatArea.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        chatArea.setBackground(Color.WHITE);

        scrollPane = new JScrollPane(chatArea);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        inputField = new JTextField();
        inputField.setFont(new Font("微软雅黑", Font.PLAIN, 12));

        sendButton = new JButton("发送");
        sendButton.setEnabled(false);

        disconnectButton = new JButton("退出");

        // 初始化在线用户列表组件
        onlineUsersModel = new DefaultListModel<>();
        onlineUsersList = new JList<>(onlineUsersModel);
        onlineUsersList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        onlineUsersScrollPane = new JScrollPane(onlineUsersList);
        onlineUsersScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        onlineUsersScrollPane.setPreferredSize(new Dimension(150, 0));
        onlineUsersScrollPane.setBorder(BorderFactory.createTitledBorder("在线用户"));
    }

    private void setupLayout() {
        // 设置登录界面布局
        loginPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);

        gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2;
        loginPanel.add(loginTitleLabel, gbc);

        gbc.gridwidth = 1; gbc.gridy = 1;
        loginPanel.add(new JLabel("用户名:"), gbc);

        gbc.gridx = 1;
        loginPanel.add(loginUsernameField, gbc);

        gbc.gridx = 0; gbc.gridy = 2;
        loginPanel.add(new JLabel("密码:"), gbc);

        gbc.gridx = 1;
        loginPanel.add(loginPasswordField, gbc);

        gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 2;
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
        buttonPanel.add(loginButton);
        loginPanel.add(buttonPanel, gbc);

        gbc.gridy = 4;
        loginPanel.add(switchToRegisterButton, gbc);

        // 设置注册界面布局
        registerPanel.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);

        gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2;
        registerPanel.add(new JLabel("用户注册", SwingConstants.CENTER), gbc);

        gbc.gridwidth = 1; gbc.gridy = 1;
        registerPanel.add(new JLabel("用户名:"), gbc);

        gbc.gridx = 1;
        registerPanel.add(registerUsernameField, gbc);

        gbc.gridx = 0; gbc.gridy = 2;
        registerPanel.add(new JLabel("密码:"), gbc);

        gbc.gridx = 1;
        registerPanel.add(registerPasswordField, gbc);

        gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 2;
        registerPanel.add(registerButton, gbc);

        gbc.gridy = 4;
        registerPanel.add(switchToLoginButton, gbc);

        // 设置连接界面布局
        connectPanel.setLayout(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);

        gbc.gridx = 0; gbc.gridy = 0;
        connectPanel.add(serverInfoLabel, gbc);

        gbc.gridx = 0; gbc.gridy = 1;
        connectPanel.add(connectServerButton, gbc);

        // 设置聊天界面布局（包含在线用户列表）
        chatPanel = new JPanel(new BorderLayout());

        // 创建主聊天区域面板（包含聊天记录和输入框）
        JPanel mainChatPanel = new JPanel(new BorderLayout());

        // 聊天区域
        mainChatPanel.add(scrollPane, BorderLayout.CENTER);

        // 底部面板
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.add(inputField, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel2.add(disconnectButton);
        buttonPanel2.add(sendButton);
        bottomPanel.add(buttonPanel2, BorderLayout.EAST);

        mainChatPanel.add(bottomPanel, BorderLayout.SOUTH);

        // 将主聊天面板和在线用户列表添加到聊天面板
        chatPanel.add(mainChatPanel, BorderLayout.CENTER);
        chatPanel.add(onlineUsersScrollPane, BorderLayout.EAST);

        // 添加面板到主面板
        mainPanel.add(loginPanel, "LOGIN_PANEL");
        mainPanel.add(registerPanel, "REGISTER_PANEL");
        mainPanel.add(connectPanel, "CONNECT_PANEL");
        mainPanel.add(chatPanel, "CHAT_PANEL");

        add(mainPanel, BorderLayout.CENTER);
    }

    private void setupEventHandlers() {
        // 登录按钮事件
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performLogin();
            }
        });

        // 注册按钮事件
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performRegister();
            }
        });

        // 切换到注册界面事件
        switchToRegisterButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(mainPanel, "REGISTER_PANEL");
            }
        });

        // 切换到登录界面事件
        switchToLoginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(mainPanel, "LOGIN_PANEL");
            }
        });

        // 连接按钮事件
        connectServerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                connectToServer();
            }
        });

        // 断开连接按钮事件
        disconnectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                disconnectFromServer();
            }
        });

        // 发送按钮事件
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });

        // 输入框回车事件
        inputField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (sendButton.isEnabled()) {
                    sendMessage();
                }
            }
        });

        // 窗口关闭事件
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                if (isConnected && channel != null) {
                    channel.close();
                }
                System.exit(0);
            }
        });
    }

    private void setupWindowProperties() {
        setTitle("RickyChat");
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setSize(800, 500);
        setLocationRelativeTo(null);
        setResizable(true);

        // 默认显示登录界面
        cardLayout.show(mainPanel, "LOGIN_PANEL");
    }

    /**
     * 执行登录操作
     */
    private void performLogin() {
        String username = loginUsernameField.getText().trim();
        String password = new String(loginPasswordField.getPassword());

        if (username.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名和密码不能为空", "登录失败", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 这里应该调用实际的登录逻辑
        // 登录成功后直接连接服务器
        currentUser = username;
        setTitle("RickyChat-当前用户"+currentUser);
        connectToServer(); // 直接调用连接服务器方法
    }

    /**
     * 执行注册操作
     */
    private void performRegister() {
        String username = registerUsernameField.getText().trim();
        String password = new String(registerPasswordField.getPassword());

        if (username.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名和密码不能为空", "注册失败", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 这里应该调用实际的注册逻辑
        JOptionPane.showMessageDialog(this, "注册成功，请登录", "注册成功", JOptionPane.INFORMATION_MESSAGE);
        cardLayout.show(mainPanel, "LOGIN_PANEL");
    }

    /**
     * 连接到服务器
     */
    private void connectToServer() {
        // 更新登录按钮状态，显示连接中
        loginButton.setText("登录中...");
        loginButton.setEnabled(false);

        SwingWorker<Channel, Void> worker = new SwingWorker<Channel, Void>() {
            @Override
            protected Channel doInBackground() throws Exception {
                return RickyClient.connectAndGetChannel();
            }

            @Override
            protected void done() {
                try {
                    channel = get();
                    if (channel != null && channel.isActive()) {
                        isConnected = true;
                        sendButton.setEnabled(true);
                        //appendMessage("系统", "已连接到服务器 " + JsonClient.SERVER_IP + ":" + JsonClient.SERVER_PORT);
                        appendMessage("系统", "已连接到服务器 " + RickyClient.SERVER_IP);
                        inputField.requestFocus();

                        // 添加示例在线用户（实际应该从服务器获取）
                        //addOnlineUser("用户1");
                        //addOnlineUser("用户2");
                        //addOnlineUser("用户3");
                        addOnlineUser(currentUser);

                        // 切换到聊天界面
                        cardLayout.show(mainPanel, "CHAT_PANEL");
                    } else {
                        appendMessage("系统", "连接服务器失败");
                    }
                } catch (Exception e) {
                    appendMessage("系统", "连接失败: " + e.getMessage());
                    LOGGER.error("连接服务器异常", e);
                } finally {
                    // 恢复登录按钮状态
                    SwingUtilities.invokeLater(() -> {
                        loginButton.setText("登录");
                        loginButton.setEnabled(true);
                    });
                }
            }
        };
        worker.execute();
    }

    /**
     * 断开服务器连接
     */
    private void disconnectFromServer() {
        if (channel != null) {
            channel.close();
        }
        isConnected = false;
        channel = null;
        sendButton.setEnabled(false);
        appendMessage("系统", "已断开服务器连接");

        // 清空在线用户列表
        clearOnlineUsers();

        // 重置登录按钮状态
        loginButton.setText("登录");
        loginButton.setEnabled(true);

        // 切换回登录界面
        cardLayout.show(mainPanel, "LOGIN_PANEL");
    }

    /**
     * 发送消息
     */
    private void sendMessage() {
        String content = inputField.getText().trim();
        if (!content.isEmpty() && channel != null && channel.isActive()) {
            JsonMsgDto jsonMsgDto = new JsonMsgDto();
            jsonMsgDto.setContent(content);
            jsonMsgDto.setUserName(currentUser != null ? currentUser : "client_user");

            channel.writeAndFlush(jsonMsgDto);
            //appendMessage("我", content);
            inputField.setText("");
        }
    }

    /**
     * 添加收到的消息到聊天区域
     * @param sender 发送者
     * @param content 消息内容
     */
    public static void appendMessage(String sender, String content) {
        SwingUtilities.invokeLater(() -> {
            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
            chatArea.append(String.format("[%s] %s: %s%n", time, sender, content));
            chatArea.setCaretPosition(chatArea.getDocument().getLength());
        });
    }

    /**
     * 更新连接状态
     */
    public void updateConnectionStatus(boolean connected) {
        SwingUtilities.invokeLater(() -> {
            isConnected = connected;
            sendButton.setEnabled(connected);
            if (!connected) {
                appendMessage("系统", "与服务器的连接已断开");
                // 清空在线用户列表
                clearOnlineUsers();
                // 切换回登录界面而不是连接界面
                cardLayout.show(mainPanel, "LOGIN_PANEL");
            }
        });
    }

    /**
     * 添加在线用户
     * @param username 用户名
     */
    public void addOnlineUser(String username) {
        SwingUtilities.invokeLater(() -> {
            if (!onlineUsersModel.contains(username)) {
                onlineUsersModel.addElement(username);
            }
        });
    }

    /**
     * 移除在线用户
     * @param username 用户名
     */
    public void removeOnlineUser(String username) {
        SwingUtilities.invokeLater(() -> {
            onlineUsersModel.removeElement(username);
        });
    }

    /**
     * 清空在线用户列表
     */
    public void clearOnlineUsers() {
        SwingUtilities.invokeLater(() -> {
            onlineUsersModel.clear();
        });
    }
}